from django.contrib import admin
from django.db import models
from django import forms
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.forms import Textarea
from django.utils.safestring import mark_safe
from storage.models import App, Level, Sound
from django.core.urlresolvers import reverse
from django.contrib import messages
from sortedm2m_filter_horizontal_widget.forms import SortedFilteredSelectMultiple
from storage.forms import LevelForm, SoundForm
from django.db.models import Case, When

class AppAdmin(admin.ModelAdmin):
    def formfield_for_manytomany(self, db_field, request=None, **kwargs):
        if db_field.name == 'level_order':
            kwargs['widget'] = SortedFilteredSelectMultiple()
        return super(AppAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)

    class Media:
        js = ("https://www.gstatic.com/firebasejs/4.2.0/firebase.js",
              'https://www.gstatic.com/firebasejs/4.2.0/firebase-app.js',
              'https://www.gstatic.com/firebasejs/4.2.0/firebase-auth.js',
              'https://www.gstatic.com/firebasejs/4.2.0/firebase-storage.js',
              "/static/firebase-diff.js",
              "/static/app-diff.js",
              "/static/jszip-utils.min.js",
              "/static/jszip.min.js",
              "/static/FileSaver.js")

class LevelAdmin(admin.ModelAdmin):
    list_display = ('name', 'display', 'sound', )
    readonly_fields = ('display',)
    list_filter = ['sound', ]
    list_editable = ['sound', ]
    actions = ['change_sound', ]
    search_fields = ['name', ]

    list_per_page = 40

    def get_queryset(self, request):
        app = App.objects.filter(name='BIGB6001').first()
        level_order = []
        for level in app.level_order.all():
            level_order.append(level.id)

        preserved = Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(level_order)])
        queryset = super(LevelAdmin, self).get_queryset(request)
        queryset = queryset.filter(pk__in=level_order).order_by(preserved)
        return queryset

    class levels_form(forms.forms.Form):
        _selected_action = forms.CharField(widget=forms.MultipleHiddenInput)
        data_src = forms.ModelChoiceField(Sound.objects)

    def change_sound(modeladmin, request, queryset):
        form = None
        if 'cancel' in request.POST:
            modeladmin.message_user(request, u'Action canceled.')
            return
        elif 'data_src' in request.POST:
            form = modeladmin.levels_form(request.POST)
            if form.is_valid():
                data_src = form.cleaned_data['data_src']
                for selected in queryset:
                    selected.sound = data_src
                    selected.save()
                modeladmin.message_user(
                    request, "%s item(s) successfully updated." % queryset.count())
                return HttpResponseRedirect(request.get_full_path())
            else:
                messages.warning(request, u"Sound must be selected. ")
                form = None

        if not form:
            form = modeladmin.levels_form(
                initial={'_selected_action': request.POST.getlist(admin.ACTION_CHECKBOX_NAME)})
        return render_to_response('batch_update.html',
                                  {'objs': queryset, 'form': form, 'path': request.get_full_path(
                                  ), 'action': 'change_sound', 'title': u'Change sound'},
                                  context_instance=RequestContext(request))
    change_sound.short_description = u'Change sound'

    class Media:
        js = ("https://www.gstatic.com/firebasejs/4.2.0/firebase.js",
              'https://www.gstatic.com/firebasejs/4.2.0/firebase-app.js',
              'https://www.gstatic.com/firebasejs/4.2.0/firebase-auth.js',
              'https://www.gstatic.com/firebasejs/4.2.0/firebase-storage.js',
              "/static/firebase-diff.js",
              "/static/level-diff.js")

class SoundAdmin(admin.ModelAdmin):
    class Media:
        js = ("https://www.gstatic.com/firebasejs/4.2.0/firebase.js",
              'https://www.gstatic.com/firebasejs/4.2.0/firebase-app.js',
              'https://www.gstatic.com/firebasejs/4.2.0/firebase-auth.js',
              'https://www.gstatic.com/firebasejs/4.2.0/firebase-storage.js',
              "/static/firebase-diff.js",
              "/static/sound-diff.js")

admin.site.register(App, AppAdmin)
admin.site.register(Level, LevelAdmin, form = LevelForm)
admin.site.register(Sound, SoundAdmin, form = SoundForm)

admin.site.site_title = 'Diff admin'
admin.site.site_header = 'Diff'